// 诗经数据，按风、雅、颂分类
const shijingData = {
    "风": {
        "周南": [
            {
                title: "关雎",
                englishTitle: "Cooing and Wooing",
                introduction: "写“君子”思慕“淑女”的心情，并想象得到她以后的快乐。",
                chinese: "关关雎鸠，在河之洲。\n窈窕淑女，君子好逑。\n"+
                "参差荇菜，左右流之。\n窈窕淑女，寤寐求之。\n"+
                "求之不得，寤寐思服。\n悠哉悠哉，辗转反侧。\n"+
                "参差荇菜，左右采之。\n窈窕淑女，琴瑟友之。\n"+
                "参差荇菜，左右芼之。\n窈窕淑女，钟鼓乐之。",
                english: "By riverside a pair,\n"+
                "Of turtledoves are cooing;\n"+
                "There is a maiden fair,\n"+
                "Whom a young man is wooing.\n"+
                "Water flows left and right,\n"+
                "Of cresses here and there;\n"+
                "The youth yearns day and night,\n"+
                "For the maiden so fair.\n"+
                "His yearning grows so strong,\n"+
                "He cannot fall asleep,\n"+
                "But tosses all night long,\n"+
                "So deep in love, so deep!\n"+
                "Now gather left and right,\n"+
                "Cress long or short and tender!\n"+
                "O lute, play music light,\n"+
                "For the fiancée so slender!\n"+
                "Feast friends at left and right,\n"+
                "On cresses cooked tender!\n"+
                "O bells and drums, delight.\n"+
                "The bride so sweet and slender!"
            },
            
        ],
        "秦风": [
            
        ]
    },
    "雅": {
        "小雅": [
            
        ],
        "大雅": [
            
        ]
    },
    "颂": {
        "周颂": [
            
        ],
        "鲁颂": [
            
        ],
        "商颂": [
            
        ]
    }
};

// 古代词汇翻译字典（支持多字词语）
const chineseTranslationDict = {
    "关关": "关关：形容水鸟的和鸣声",
    "雎鸠": "雎鸠：一种水鸟",
    "洲": "河中沙洲",
    "窈窕": "窈窕：娴静美好的样子",
    "淑": "善也",
    "好逑": "好逑：佳偶",
    "参差": "参差（cēn cī）：长短不齐",
    "荇菜": "荇菜：一种水草，可食",
    "流": "通“捞”",
    "寤": "醒来",
    "寐": "睡着",
    "思服": "思服：思念",
    "悠哉": "悠哉：思念之深长",
    "辗转反侧": "辗（zhǎn）转反侧：形容睡不着",
    "琴瑟": "琴瑟：乐器，动词用，或喻和谐",
    "友": "亲密，亲近",
    "芼": "通“摸”，水下摸索荇菜之意",
    "乐": "愉悦，或通“撩”，以音乐追求女子的方式",
};

// 单词翻译词典
const englishTranslationDict = {
    "riverside": "河边；河畔",
    "turtledoves": "斑鸠；情人",
    "cooing": "咕咕叫；温声细语",
    "maiden": "少女；处女",
    "fair": "美丽的；公平的",
    "wooing": "求爱，追求",
    "cresses": "水芹",
    "youth": "青年；小伙子",
    "yearns": "渴望，向往",
    "tosses": "摇动，摆动",
    "gather": "收集，采集",
    "tender": "嫩的，软的；温柔的，亲切的",
    "lute": "琵琶；弹诗琴",
    "light": "轻柔的；愉快的",
    "fiancée": "未婚妻",
    "slender": "苗条的，纤细的",
    "Feast": "宴请，设宴招待",
    "bells": "铃；排钟",
    "drums": "鼓；打鼓",
    "delight": "高兴；使高兴",
    "bride": "新娘",
};

// DOM元素
const categoryList = document.getElementById('categoryList');
const chineseContent = document.getElementById('chineseContent');
const englishContent = document.getElementById('englishContent');
const pinyinToggle = document.getElementById('pinyinToggle');
const poemInfo = document.getElementById('poemInfo');
const englishTitle = document.getElementById('englishTitle');
const poemIntro = document.getElementById('poemIntro');
    
let showPinyin = true;
let currentCategory = null;
let currentSubcategory = null;
let currentPoem = null;
    
// 渲染分类列表
function renderCategories() {
    let html = '';
    const categories = Object.keys(shijingData);
        
    categories.forEach(category => {
        const subcategories = Object.keys(shijingData[category]);
        let icon = '';
        
        switch(category) {
            case "风":
                icon = '<i class="fas fa-wind category-icon"></i>';
                break;
            case "雅":
                icon = '<i class="fas fa-feather-alt category-icon"></i>';
                break;
            case "颂":
                icon = '<i class="fas fa-drum category-icon"></i>';
                break;
        }
        
        html += `
            <li class="category-item" data-category="${category}">
                ${icon}${category}
                <ul class="poem-list">
                    ${subcategories.map(sub => `
                        <li class="subcategory-item" data-category="${category}" data-subcategory="${sub}">
                            ${sub}
                            <ul class="poem-sublist">
                                ${shijingData[category][sub].map((poem, index) => `
                                    <li class="poem-item" 
                                        data-category="${category}" 
                                        data-subcategory="${sub}"
                                        data-index="${index}">
                                        ${poem.title}
                                    </li>
                                `).join('')}
                            </ul>
                        </li>
                    `).join('')}
                </ul>
            </li>
        `;
    });
        
    categoryList.innerHTML = html;
        
    // 添加分类点击事件
    document.querySelectorAll('.category-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.stopPropagation();
            const category = this.getAttribute('data-category');
        
            // 移除所有active类
            document.querySelectorAll('.category-item').forEach(i => {
                i.classList.remove('active');
            });
        
            // 添加active类
            this.classList.add('active');
            currentCategory = category;
            currentSubcategory = null;
            currentPoem = null;
        
            // 更新信息
            poemInfo.textContent = `已选择分类：${category}`;
        
            // 清空内容
            chineseContent.innerHTML = '<p>请选择子分类和具体诗篇</p>';
            englishContent.innerHTML = '<p>Please select a subcategory and poem</p>';
            englishTitle.textContent = '';
        
            // 更新简介
            updateIntroduction(category);
        });
    });
        
    // 添加子分类点击事件
    document.querySelectorAll('.subcategory-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.stopPropagation();
            const category = this.getAttribute('data-category');
            const subcategory = this.getAttribute('data-subcategory');
        
            // 移除所有active类
            document.querySelectorAll('.subcategory-item').forEach(i => {
                i.classList.remove('active');
            });
        
            // 添加active类
            this.classList.add('active');
            currentCategory = category;
            currentSubcategory = subcategory;
            currentPoem = null;
        
            // 更新信息
            poemInfo.textContent = `已选择：${category} · ${subcategory}`;
        
            // 清空内容
            chineseContent.innerHTML = '<p>请选择具体诗篇</p>';
            englishContent.innerHTML = '<p>Please select a poem</p>';
            englishTitle.textContent = '';
        
            // 更新简介
            updateIntroduction(category, subcategory);
        });
    });
        
    // 添加诗歌点击事件
    document.querySelectorAll('.poem-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.stopPropagation();
            const category = this.getAttribute('data-category');
            const subcategory = this.getAttribute('data-subcategory');
            const index = parseInt(this.getAttribute('data-index'));
        
            // 移除所有active类
            document.querySelectorAll('.poem-item').forEach(i => {
                i.classList.remove('active');
            });
        
            // 添加active类
            this.classList.add('active');
        
            // 渲染诗歌
            renderPoem(category, subcategory, index);
        });
    });
}

// 更新简介
function updateIntroduction(category, subcategory = null, poem = null) {
    let introHTML = '';
        
    if (!category) {
        introHTML = `
            <h3 class="intro-title">《诗经》简介</h3>
            <div class="intro-content">
                <p>《诗经》是中国第一部诗歌总集，收录了自西周初年至春秋中叶的诗歌 305 篇，分为风、雅、颂三部分。</p>
                <p>风：也称为国风，是采集自各地的民间歌谣；雅：周王畿内乐调，多为贵族宴饮乐歌；颂：用于宗庙祭祀的乐歌。</p>
            </div>
        `;
    } else if (poem) {
        introHTML = `
            <h3 class="intro-title">诗篇简介</h3>
            <div class="intro-content">
                <p>${poem.introduction}</p>
            </div>
        `;
    } else if (category && !subcategory) {
        let categoryDesc = '';
        switch(category) {
            case "风":
                categoryDesc = "《风》，也称为《国风》，作为《诗经》中的核心内容，是采集自不同地区的民间歌谣，共 160 篇。";
                break;
            case "雅":
                categoryDesc = "《雅》，为周王朝直辖地区的正声雅乐，分《大雅》和《小雅》，共 105 篇。";
                break;
            case "颂":
                categoryDesc = "《颂》，包括《周颂》、《鲁颂》和《商颂》，共 40 篇，是用于宗庙祭祀的乐歌。";
                break;
        }
        
        introHTML = `
            <h3 class="intro-title">《${category}》简介</h3>
            <div class="intro-content">
                <p>${categoryDesc}</p>
            </div>
        `;
    } else if (category && subcategory) {
        let subDesc = '';
        switch(subcategory) {
            case "周南":
                subDesc = "《周南》包括《关雎》等 11 首诗，采集于周公统治下的南方地区的民歌，地理范围包括今河南西南部及湖北西北部等地。";
                break;
            case "秦风":
                subDesc = "《秦风》包括《车邻》等 10 首诗，采集于秦地，即今甘肃、陕西一带。";
                break;
            case "小雅":
                subDesc = "《小雅》存诗 74 篇，内容除反映国事及贵族生活外，多怨诽之辞，其中也包含部分民歌。";
                break;
            case "大雅":
                subDesc = "《大雅》存诗 31 篇，主题多与周王室历史及政治、军事、祭祀等活动相关，诗风雍容典雅。";
                break;
            case "周颂":
                subDesc = "《周颂》共 31 篇，是周王朝的宗庙祭祀乐歌。";
                break;
            case "鲁颂":
                subDesc = "《鲁颂》共 4 篇，其体制及风格与《周颂》不同，并非祭祀乐歌。";
                break;
        }
        
        introHTML = `
            <h3 class="intro-title">《${category} · ${subcategory}》简介</h3>
            <div class="intro-content">
                <p>${subDesc}</p>
            </div>
        `;
    }
        
    poemIntro.innerHTML = introHTML;
}
    
// 渲染诗歌
function renderPoem(category, subcategory, index) {
    const poem = shijingData[category][subcategory][index];
    currentPoem = poem;
        
    // 更新信息
    poemInfo.textContent = `正在赏析：${category} · ${subcategory} · ${poem.title}`;
        
    // 设置英文标题
    englishTitle.textContent = poem.englishTitle;
        
    // 更新简介
    updateIntroduction(category, subcategory, poem);
        
    // 渲染中文内容（根据注音状态）
    if (showPinyin) {
        renderChineseWithPinyin(poem.chinese);
    } else {
        renderChineseWithoutPinyin(poem.chinese);
    }
        
    // 渲染英文内容
    renderEnglish(poem.english);
}
    
// 判断是否为标点符号
function isPunctuation(char) {
    const punctuations = /[，。、：；！？《》「」『』【】〔〕“”‘’]/;
    return punctuations.test(char);
}
    
// 高级分词算法（支持多字词语）
function tokenizeText(text) {
    const tokens = [];
    const words = Object.keys(chineseTranslationDict).sort((a, b) => b.length - a.length);
    let i = 0;
        
    while (i < text.length) {
        let matched = false;
        
        // 跳过空格
        if (text[i] === ' ' || text[i] === '\n') {
            tokens.push({ type: 'space', value: text[i] });
            i++;
            continue;
        }
        
        // 跳过标点
        if (isPunctuation(text[i])) {
            tokens.push({ type: 'punctuation', value: text[i] });
            i++;
            continue;
        }
        
        // 尝试匹配多字词语
        for (let j = 0; j < words.length; j++) {
            const word = words[j];
            if (text.substring(i, i + word.length) === word) {
                tokens.push({
                    type: 'word',
                    value: word,
                    translation: chineseTranslationDict[word]
                });
                i += word.length;
                matched = true;
                break;
            }
        }
        
        // 如果没有匹配到多字词语，则按单字处理
        if (!matched) {
            tokens.push({
                type: 'char',
                value: text[i],
                translation: chineseTranslationDict[text[i]] || null
            });
            i++;
        }
    }
        
    return tokens;
}
    
// 渲染带拼音的中文
function renderChineseWithPinyin(text) {
    const lines = text.split('\n');
    let html = '';
        
    lines.forEach(line => {
        if (line.trim() === '') return;
            
        html += '<div class="poem-line">';
        const tokens = tokenizeText(line);
            
        tokens.forEach(token => {
            if (token.type === 'space') {
                html += '&nbsp;';
            } else if (token.type === 'punctuation') {
                // 标点符号使用单独的样式
                html += `<span class="chinese-punctuation">${token.value}</span>`;
            } else if (token.type === 'word') {
                // 处理多字词语
                let wordHtml = '';
                for (let char of token.value) {
                    const pinyin = pinyinPro.pinyin(char, { toneType: 'symbol' });
                        
                    // 只为有翻译的词语添加has-translation类
                    if (token.translation) {
                        wordHtml += `
                            <span class="chinese-char has-translation" data-trans="${token.translation}">
                                <div class="pinyin-container">
                                    <span class="pinyin">${pinyin}</span>
                                </div>
                                ${char}
                            </span>
                        `;
                    } else {
                        wordHtml += `
                            <span class="chinese-char">
                                <div class="pinyin-container">
                                    <span class="pinyin">${pinyin}</span>
                                </div>
                                ${char}
                            </span>
                        `;
                    }
                }
                html += wordHtml;
            } else if (token.type === 'char') {
                const pinyin = pinyinPro.pinyin(token.value, { toneType: 'symbol' });
                    
                // 只为有翻译的单字添加has-translation类
                if (token.translation) {
                    html += `
                        <span class="chinese-char has-translation" data-trans="${token.translation}">
                            <div class="pinyin-container">
                                <span class="pinyin">${pinyin}</span>
                            </div>
                            ${token.value}
                        </span>
                    `;
                } else {
                    html += `
                        <span class="chinese-char">
                            <div class="pinyin-container">
                                <span class="pinyin">${pinyin}</span>
                            </div>
                            ${token.value}
                        </span>
                    `;
                }
            }
        });
            
        html += '</div>';
    });
        
    chineseContent.innerHTML = html;
        
    // 添加中文词汇点击事件
    addChineseWordEvents();
}
    
// 渲染不带拼音的中文
function renderChineseWithoutPinyin(text) {
    const lines = text.split('\n');
    let html = '';
        
    lines.forEach(line => {
        if (line.trim() === '') return;
            
        html += '<div class="poem-line">';
        const tokens = tokenizeText(line);
            
        tokens.forEach(token => {
            if (token.type === 'space') {
                html += '&nbsp;';
            } else if (token.type === 'punctuation') {
                // 标点符号使用单独的样式
                html += `<span class="chinese-punctuation">${token.value}</span>`;
            } else if (token.type === 'word') {
                // 处理多字词语
                let wordHtml = '';
                for (let char of token.value) {
                    // 只为有翻译的词语添加has-translation类
                    if (token.translation) {
                        wordHtml += `<span class="chinese-char has-translation" data-trans="${token.translation}">${char}</span>`;
                    } else {
                        wordHtml += `<span class="chinese-char">${char}</span>`;
                    }
                }
                html += wordHtml;
            } else if (token.type === 'char') {
                // 只为有翻译的单字添加has-translation类
                if (token.translation) {
                    html += `<span class="chinese-char has-translation" data-trans="${token.translation}">${token.value}</span>`;
                } else {
                    html += `<span class="chinese-char">${token.value}</span>`;
                }
            }
        });
            
        html += '</div>';
    });
        
    chineseContent.innerHTML = html;
        
    // 添加中文词汇点击事件
    addChineseWordEvents();
}
    
// 添加中文词汇点击事件（只对有注释的文字）
function addChineseWordEvents() {
    document.querySelectorAll('.chinese-char.has-translation').forEach(char => {
        const translation = char.getAttribute('data-trans');
        if (translation) {
            char.addEventListener('click', function(e) {
                showTranslationPopup(e, translation);
            });
        }
    });
}
    
// 渲染英文内容并添加单词翻译功能
function renderEnglish(text) {
    const lines = text.split('\n');
    let html = '';
        
    lines.forEach(line => {
        if (line.trim() === '') return;
            
        html += '<div class="english-line">';
        const words = line.split(/\s+/);
            
        words.forEach(word => {
            // 清理单词中的标点符号
            const cleanWord = word.replace(/[.,!?;:']/g, '');
                
            if (englishTranslationDict[cleanWord] || englishTranslationDict[cleanWord.toLowerCase()]) {
                const translation = englishTranslationDict[cleanWord] || englishTranslationDict[cleanWord.toLowerCase()];
                html += `
                    <span class="english-word" data-trans="${translation}">
                        ${word}
                    </span>
                `;
            } else {
                html += `<span>${word}</span>`;
            }
            html += ' ';
        });
            
        html += '</div>';
    });
        
    englishContent.innerHTML = html;
        
    // 添加单词点击事件
    document.querySelectorAll('.english-word').forEach(word => {
        word.addEventListener('click', function(e) {
            const translation = this.getAttribute('data-trans');
            showTranslationPopup(e, translation);
        });
    });
}
    
// 显示翻译弹窗
function showTranslationPopup(event, translation) {
    // 移除现有的弹窗
    document.querySelectorAll('.translation-popup').forEach(popup => {
        popup.remove();
    });
        
    // 创建新弹窗
    const popup = document.createElement('div');
    popup.className = 'translation-popup';
    popup.textContent = translation;
        
    // 定位弹窗
    const rect = event.target.getBoundingClientRect();
    popup.style.position = 'fixed';
    popup.style.left = `${rect.left + rect.width/2}px`;
    popup.style.top = `${rect.top - 40}px`; // 调整弹窗位置，避免重叠
        
    document.body.appendChild(popup);
        
    // 3秒后移除弹窗
    setTimeout(() => {
        popup.remove();
    }, 3000);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 渲染分类列表
    renderCategories();
        
    // 更新简介
    updateIntroduction();
        
    // 注音切换按钮事件
    pinyinToggle.addEventListener('click', () => {
        showPinyin = !showPinyin;
        if (showPinyin) {
            pinyinToggle.innerHTML = '<i class="fas fa-chinese-yuan"></i><span>关闭注音模式</span>';
            pinyinToggle.classList.remove('active');
        } else {
            pinyinToggle.innerHTML = '<i class="fas fa-chinese-yuan"></i><span>开启注音模式</span>';
            pinyinToggle.classList.add('active');
        }
            
        // 如果当前有诗歌被选中，重新渲染
        if (currentPoem) {
            if (showPinyin) {
                renderChineseWithPinyin(currentPoem.chinese);
            } else {
                renderChineseWithoutPinyin(currentPoem.chinese);
            }
        }
    });
        
    // 参考文献按钮事件
    const referencesToggle = document.getElementById('referencesToggle');
    const referencesCard = document.getElementById('referencesCard');
        
    referencesToggle.addEventListener('click', function() {
        referencesCard.classList.toggle('active');
        // 切换按钮文字
        const span = this.querySelector('span');
        if (referencesCard.classList.contains('active')) {
            span.textContent = '收起参考文献';
        } else {
            span.textContent = '参考文献';
        }
    });
});  